<?php

class IkebanaService extends AbstractService
{
    /**
     * @var IkebanaService
     */
    private static $instance;

    /**
     * Get the instance of IkebanaService.
     *
     * @return IkebanaService
     */
    public static function get()
    {
        if (!self::$instance) {
            self::$instance = new IkebanaService();
        }
        return self::$instance;
    }

    /**
     * Construction.
     */
    protected function __construct()
    {
        parent::__construct();
    }

    /**
     * 处理创建时的逻辑
     *
     * @param int $shardId
     * @return void
     */
    public function handleCreate($shardId)
    {

    }

    /**
     * 处理登录时的逻辑
     *
     * @param int $userId
     * @return void
     */
    public function handleLogin($userId)
    {
    }

    /**
     * 提供当前 service 数据
     *
     * @param int $userId
     * @param boolean $visitMode default false
     * @return array()
     */
    public function info($userId, $visitMode = false)
    {
        return [
            SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_IKEBANA)
        ];
    }

    /**
     * 解锁保存队列
     * @param $userId
     * @param $type
     * @param $unlockIndex 0起
     * @param $reqTime
     * @throws SzException
     * @return bool
     */
    public function unlockQueue($userId, $type, $unlockIndex, $reqTime)
    {
        $workLatticeConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_IKEBANA_LATTICE, $type, true);
        /**
         * @var $ikebanaVoList IkebanaVoList
         * @var $ikebanaVo IkebanaVo
         */
        $ikebanaVoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_IKEBANA);
        $ikebanaVo = $ikebanaVoList->getElement($type, false);
        if (!$ikebanaVo) {
            $defaultLattice = [];
            foreach ($workLatticeConfig['price'] as $price) {
                if ($price == 0) {
                    $defaultLattice[] = -1;
                }
            }
            SzLogger::get()->debug("qf---combinationIds---" . var_export($defaultLattice, true) . "------");
            $ikebanaVo = new IkebanaVo($userId, $type, json_encode($defaultLattice), $reqTime, true);
        }
        $combinationIds = $ikebanaVo->getRawCombinationIds();
        if (isset($combinationIds[$unlockIndex]) || $workLatticeConfig['quantity'] - 1 < $unlockIndex) {
            throw new SzException(28003, $unlockIndex);
        }
        $workLatticeConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_IKEBANA_LATTICE, $type, true);
        $price = $workLatticeConfig['price'][$unlockIndex];
        GameService::get()->handleEntity($userId, GameConst::ENTITY_ACTION_CONSUME_MONEY, $price, true);
        SzLogger::get()->debug("qf---combinationIds---" . var_export($combinationIds, true) . "------");
        SzLogger::get()->debug("qf---unlockIndex---" . var_export($unlockIndex, true) . "------");
        $combinationIds[$unlockIndex] = -1;
        SzLogger::get()->debug("qf------" . var_export($combinationIds, true) . "------");
        $ikebanaVo->setCombinationIds($combinationIds);
        if ($ikebanaVo->isInsert() && !SzUtility::checkArrayKey($type, $ikebanaVoList->getList())) {
            $ikebanaVoList->addElement($ikebanaVo);
            $ikebanaVoList->setElement($type, $ikebanaVo);
        } else {
            $ikebanaVoList->updateElement($type, $ikebanaVo);
        }
        SzPersister::get()->setVoList($ikebanaVoList);

        $count = count($combinationIds);
        // 数据采集:扩充作品格子
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:mix|action:expand|',
                'item' => $count,
                'value' => 1
            )
        ));


        // 数据采集:插花作品扩充格子
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_UPGRADE, array(
            'clientData' => array(
                'tid' => 'objective:mix|item:expand|',
                'item' => 'fromlevel:' . ($count - 1) . '|changelev:1|targetlev:' . $count . '|',
                'value' => 1
            )
        ));

        // 数据采集:扩充作品格子消耗钻石数
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USE_GOLD, array(
            'clientData' => array(
                'tid' => '',
                'item' => 'mix_expand&' . $count
            )
        ));
        return true;
    }

    /**
     * 制作插花
     * @param $userId
     * @param $vaseId
     * @param $type
     * @param $count
     * @param $combinationId
     * @param $reqTime
     * @throws SzException
     * @return bool
     */
    public function make($userId, $vaseId, $type, $count, $combinationId, $reqTime)
    {
        //验证该模式是否可以用该花瓶
        $ikebanaVaseConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_IKEBANA_ARRANGEMENT_ONE, $vaseId, true);
        if (!in_array($type, $ikebanaVaseConfig['types'])) {
            throw new SzException(28005, [$vaseId, $type]);
        }
        //验证该插花是否可以用该花瓶
        $ikebanaArrangementConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_IKEBANA_ARRANGEMENT_TWO, $combinationId, true);
        /**
         *  @var ModuleItemVoList $itemList
         */
        if ($ikebanaVaseConfig['unlockProps']) {
            $itemList = SzPersister::get()->getVoList($userId, ModuleItemConst::ORM_NAME_ITEM);
            $item = $itemList->getElementsByItemDefId($ikebanaVaseConfig['unlockProps']);
            if (is_null($item)) {
                throw new SzException(29002);
            }
        } else if ($ikebanaArrangementConfig['vaseCombination'][0] != $vaseId){
            throw new SzException(28001, [$vaseId, $combinationId]);
        }

        $inputTid = '';
        foreach ($ikebanaArrangementConfig['flowerCombinationId'] as $requireId => $tmpCount) {
            GameService::get()->handleEntity($userId, '7401' . $requireId, $tmpCount * $count, true);
            $inputTid .= '7401' . $requireId . ':' . abs($tmpCount * $count) . '|';
        }
        GameService::get()->handleEntity($userId, '7201' . $ikebanaArrangementConfig['vaseCombination'][1], $count, true);

        $tid = '7201' . $ikebanaArrangementConfig['vaseCombination'][1].':'.$count.'|';


        // 数据采集:制作插花作品
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:mix|action:making|',
                'item' => $vaseId . '&' . $type,
                'value' => 1
            )
        ));

        // 数据采集:制作插花作品消耗物品
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_INPUT, array(
            'clientData' => array(
                'tid' => $inputTid,
                'item' => 'mix_making&' . $vaseId . '&' . $type
            )
        ));

        // 数据采集:制作插花作品产出物品
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_RESOURCE_OUTPUT, array(
            'clientData' => array(
                'tid' => $tid,
                'item' => 'mix_making&' . $vaseId . '&' . $type
            )
        ));

        //社团竞赛任务进度添加
        UnionCompetitionService::get()->addCompetitionTaskProcess($userId,GameConst::UNION_COMPETITION_TASK_2, $reqTime,$count,$vaseId);

        return true;
    }

    /**
     * 保存插花
     * @param $userId
     * @param $vaseId
     * @param $type
     * @param $combinationId
     * @param $index
     * @param $reqTime
     * @throws SzException
     * @return bool
     */
    public function save($userId, $vaseId, $type, $combinationId, $index, $reqTime)
    {
        $ikebanaVaseConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_IKEBANA_ARRANGEMENT_ONE, $vaseId, true);
        if (!in_array($type, $ikebanaVaseConfig['types'])) {
            throw new SzException(28005, [$vaseId, $type]);
        }
        $ikebanaArrangementConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_IKEBANA_ARRANGEMENT_TWO, $combinationId, true);
        if ($ikebanaArrangementConfig['vaseCombination'][0] != $vaseId) {
            throw new SzException(28001, [$vaseId, $combinationId]);
        }
        $workLatticeConfig = SzConfig::get()->loadAppConfig(GameConst::CONFIG_IKEBANA_LATTICE, $type, true);
        /**
         * @var $ikebanaVoList IkebanaVoList
         * @var $ikebanaVo IkebanaVo
         */
        $ikebanaVoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_IKEBANA);
        $ikebanaVo = $ikebanaVoList->getElement($type, false);
        if (!$ikebanaVo) {
            $defaultLattice = [];
            foreach ($workLatticeConfig['price'] as $price) {
                if ($price == 0) {
                    $defaultLattice[] = -1;
                }
            }
            $ikebanaVo = new IkebanaVo($userId, $type, json_encode($defaultLattice), $reqTime, true);
        }
        $combinationIds = $ikebanaVo->getRawCombinationIds();
        if (!isset($combinationIds[$index]) || $combinationIds[$index] !== -1) {
            throw new SzException(28002, $index);
        }
        $combinationIds[$index] = $combinationId;
        $ikebanaVo->setCombinationIds($combinationIds);
        if ($ikebanaVo->isInsert() && !SzUtility::checkArrayKey($type, $ikebanaVoList->getList())) {
            $ikebanaVoList->addElement($ikebanaVo);
            $ikebanaVoList->setElement($type, $ikebanaVo);
        } else {
            $ikebanaVoList->updateElement($type, $ikebanaVo);
        }
        SzPersister::get()->setVoList($ikebanaVoList);

        // 数据采集:保存插花作品
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:mix|action:save|',
                'item' => $vaseId . '&' . $type,
                'value' => 1
            )
        ));
        return true;
    }

    /**
     * 删除插花
     * @param $userId
     * @param $type
     * @param $combinationId
     * @param $index
     * @param $reqTime
     * @throws SzException
     * @return bool
     */
    public function remove($userId, $type, $combinationId, $index, $reqTime)
    {
        /**
         * @var $ikebanaVoList IkebanaVoList
         * @var $ikebanaVo IkebanaVo
         */
        $ikebanaVoList = SzPersister::get()->getVoList($userId, GameConst::ORM_NAME_IKEBANA);
        $ikebanaVo = $ikebanaVoList->getElement($type);
        $combinationIds = $ikebanaVo->getRawCombinationIds();
        if (!isset($combinationIds[$index]) || $combinationIds[$index] != $combinationId) {
            throw new SzException(28004);
        }
        $combinationIds[$index] = -1;
        $ikebanaVo->setCombinationIds($combinationIds);
        $ikebanaVoList->updateElement($type, $ikebanaVo);
        SzPersister::get()->setVoList($ikebanaVoList);

        // 数据采集:重置插花作品
        StatisticsService::get()->saveLog($userId, GameConst::LOG_TYPE_USER_ORBIT, array(
            'clientData' => array(
                'tid' => 'Module:mix|action:reset|',
                'item' => $combinationId . '&' . $type,
                'value' => 1
            )
        ));
        return true;
    }
}